package com.stark.wechat.service.impl;

import java.net.UnknownHostException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.stark.wechat.dao.JobQueueMapper;
import com.stark.wechat.domain.JobQueue;
import com.stark.wechat.util.DateUtil;
import com.stark.wechat.util.Tools;

/**
 * 作业队列业务逻辑。
 * @author Ben
 * @since 1.0.0
 * @version 1.0.0, 2017/8/6
 */
@Service("jobQueueService")
public class JobQueueServiceImpl {
	Logger logger = LoggerFactory.getLogger(JobQueueServiceImpl.class);
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private JobQueueMapper jobQueueMapper;
	
	/**
	 * 计算今天当前服务器针对指定作业的报名次数。
	 * @param jobId 作业标识。
	 * @return 今天当前服务器针对指定作业的报名次数。
	 * @throws UnknownHostException 获取服务器 IP 时抛出异常。
	 */
	public int countToday(String jobId) throws UnknownHostException {
		String sql = "select count(*) CNT"
				+ " from wechat_job_queue"
				+ " where SERVER_IP = '" + Tools.getServerIp() + "' and JOB_ID = '" + jobId + "'"
				+ " and PUSH_TIME >= '" + DateUtil.getCurrDate() + " 00:00:00'";
		int cnt = this.jdbcTemplate.queryForObject(sql, Integer.class);
		return cnt;
	}
	
	/**
	 * 报名作业。
	 * @param jobId 作业标识。
	 * @param jobName 作业名称。
	 * @return 作业队列。
	 */
	public void add(String jobId, String jobName) {
		String ip = "", hostName = "";
		try {
			ip = Tools.getServerIp();
			hostName = Tools.getServerHostName();
		} catch (UnknownHostException e) {
			throw new RuntimeException("获取服务器IP、主机名失败：", e);
		}
		
		JobQueue jobQueue = new JobQueue();
		jobQueue.setServerIp(ip);
		jobQueue.setServerHost(hostName);
		jobQueue.setJobId(jobId);
		jobQueue.setJobName(jobName);
		jobQueue.setPushTime(new Date());
		this.jobQueueMapper.insert(jobQueue);
	}
	
	/**
	 * 判断当前服务器是否是指定作业当天的执行者。
	 * @param jobId 作业标识。
	 * @return 是返回 true ，否返回 false 。
	 */
	public boolean isJobExcutorToday(String jobId) {
		String ip = "";
		try {
			ip = Tools.getServerIp();
		} catch (UnknownHostException e) {
			logger.error("获取服务器 IP 失败", e);
			return false;
		}
		
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		
		Map<String, Object> params = new HashMap<>();
		params.put("jobId", jobId);
		params.put("pushTimeMin", calendar.getTime());
		List<JobQueue> list = this.jobQueueMapper.selectByParams(params);
		if (CollectionUtils.isEmpty(list)) {
			return false;
		}
		if (ip.equalsIgnoreCase(list.get(0).getServerIp())) {
			return true;
		}
		return false;
	}
}
